package com.sell.controller;

import com.sell.utils.WechatStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Author: Xukai
 * Description:
 * CreateDate: 2018/6/26 0:21
 * Modified By:
 */
@Controller
public class LinkinController {

    @RequestMapping(value = "handle", method = RequestMethod.GET)
    public void linkHandle(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

        //获取输出流
        PrintWriter out = response.getWriter();

        //如果验证消息是来自微信，返回echostr
        boolean check = WechatStringUtils.checkSignature(signature, timestamp, nonce);
        if (check) {
            out.print(echostr);
        }

        out.close();
        out = null;
    }

    /**
     * 消息的处理和响应
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "handle", method = RequestMethod.POST)
    public void messageHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //将请求、响应的编码设置为utf-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        //调用核心业务逻辑
        //String respXml = CoreService.processRequest(request);
    }
}
